package mybatis;

import mybatis.dao.EmpMapper;
import mybatis.entity.Emp;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * @author zhang peng yang ming
 * 不使用 XML 构建 SqlSessionFactory
 * @create 2018-07-22 23:29
 */
public class SqlSessionFactoryUtil2 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.load(Resources.getResourceAsStream("mybatis/db.properties"));;
        DataSource dataSource = new PooledDataSource(
                properties.getProperty("jdbc.driver"),
                properties.getProperty("jdbc.url"),
                properties.getProperty("jdbc.username"),
                properties.getProperty("jdbc.password"));

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);

        configuration.getTypeAliasRegistry().registerAlias("Emp", "mybatis.entity.Emp");
        // 注意：注册别名与add mapper 顺序不能变
//        configuration.addMapper(EmpMapper.class);
        configuration.addMappers("mybatis.dao");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession session = sqlSessionFactory.openSession();



        EmpMapper dao = session.getMapper(EmpMapper.class);
        List<Emp> emps = dao.findAll();
//        List<Emp> emps = session.selectList("mybatis.dao.EmpMapper.findAll");
        System.out.println(emps.size());
    }
}
